package com.cskaoyan.controller;

import com.cskaoyan.bean.CskaoyanmallCoupon;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.WxCouponMyListVo;
import com.cskaoyan.mapper.CskaoyanmallUserMapper;
import com.cskaoyan.service.WxCouponServiceZGY;
import com.cskaoyan.utils.QueryUserIdByUserNameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 小程序端 优惠券
 */
@RestController
@RequestMapping("wx/coupon")
public class WxCouponControllerZGY {


    @Autowired
    WxCouponServiceZGY service;

    @Autowired
    CskaoyanmallUserMapper userMapper;

    @GetMapping("mylist")
    public BaseRespVo listCoupon(Integer status, Integer page, Integer size){

        Integer userId = QueryUserIdByUserNameUtils.queryName(userMapper);


        WxCouponMyListVo wxCouponVo = service.wxListCoupon(status, page, size, userId);

        return BaseRespVo.success(wxCouponVo);
    }

    /**
     * 首页中，点击优惠券标题，显示出所有优惠券
     */
    @GetMapping("list")
    public BaseRespVo listCoupons(Integer page, Integer size){

        WxCouponMyListVo couponsVo = service.queryCoupons(page, size);

        return BaseRespVo.success(couponsVo);
    }

    /**
     * 返回 结账时，可用的优惠券
     */
    @GetMapping("selectlist")
    public BaseRespVo selectCouponList(Integer cartId, Integer grouponRulesId){

        Integer userId = QueryUserIdByUserNameUtils.queryName(userMapper);

        // TODO: 暂时写不了
        List<CskaoyanmallCoupon> coupons = service.queryAvailableCoupons(cartId, grouponRulesId, userId);

        return BaseRespVo.success(coupons);
    }

    /**
     * 在主页领取优惠券
     */
    @PostMapping("receive")
    public BaseRespVo receiveCoupon(@RequestBody Map<String,Integer> map){

        Integer userId = QueryUserIdByUserNameUtils.queryName(userMapper);

        Integer couponId = map.get("couponId");
        Boolean isSuccess = service.receiveCoupon(couponId, userId);

        if (isSuccess == false) {
//            TODO: 已领取的错误代码？
            return BaseRespVo.fail(501);
        }

        return BaseRespVo.success();
    }

    /**
     * 在个人优惠券中心 使用兑换码兑换优惠券
     */
    @PostMapping("exchange")
    public BaseRespVo exchangeCoupon(@RequestBody Map<String, String> map){

        Integer userId = QueryUserIdByUserNameUtils.queryName(userMapper);

        String code = map.get("code");

        Boolean flag = service.exchangeCoupons(code, userId);

        if (!flag) {
            return BaseRespVo.fail(742);
        }

        return BaseRespVo.success();
    }
}
